package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 
 * JDBCUtil类：访问数据库工具类
 *
 */
public class JDBCUtil {
	// 定义数据库连接参数
	private static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/newssystem";
	private static final String USERNAME = "wz";
	private static final String PASSWORD = "123456";

	// 注册数据库驱动
	static {
		try {
			Class.forName(DRIVER_CLASS_NAME);
		} catch (ClassNotFoundException e) {
			System.out.println("注册失败！");
			e.printStackTrace();
		}
	}

	// 获取连接
	public static Connection getConn() throws SQLException {
		return DriverManager.getConnection(URL, USERNAME, PASSWORD);
	}

	// 关闭连接
	public static void closeConn(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
				conn = null;
			} catch (SQLException e) {
				System.out.println("关闭连接失败！");
				e.printStackTrace();
			}
		}
	}
	
	// 关闭描述
	public static void closeStatement(Statement stat) {
		if (stat != null) {
			try {
				stat.close();
				stat = null;
			} catch (SQLException e) {
				System.out.println("关闭描述失败！");
				e.printStackTrace();
			}
		}
	}
	
	// 关闭结果集
	public static void closeResultSet(ResultSet res) {
		if (res != null) {
			try {
				res.close();
				res = null;
			} catch (SQLException e) {
				System.out.println("关闭结果集失败！");
				e.printStackTrace();
			}
		}
	}

}
